﻿#region using
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Linq;
#endregion

namespace Demo.DbmlReader
{
  class Program
  {
    // Application Entry Point

    #region Main(string[] args)
    static void Main(string[] args)
    {
      // Construct a Database object using an input XML filename

      Database sampleDb = new Database("..\\..\\Dbml\\Sample.dbml");
      Console.WriteLine();

      // Demonstrate access to the Database object using ordinary C# methods and iterators

      Console.WriteLine("Demo using ordinary object and iterator access ...");
      Console.WriteLine("--------------------------------------------------");
      Console.WriteLine("Sample Database has {0} tables", sampleDb.Tables.Count);

      foreach (Table table in sampleDb.Tables)
      {
        Console.WriteLine();
        Console.WriteLine("Table: {0}", table.Type.Name);
        foreach (Column column in table.Type.Columns)
          Console.WriteLine(" Column: {0}", column.Name);
      }

      Console.WriteLine();

      // Demonstrate access to the Database object using LINQ functionality

      Console.WriteLine("Demo using LINQ to Objects access ...");
      Console.WriteLine("-------------------------------------");
      string tableName = "InvoiceItem";

      var tables = from table in sampleDb.Tables where table.Type.Name == tableName select table;
      if (tables.Count() == 0)
      {
        Console.WriteLine("Table '{0}' not found", tableName);
        return;
      }

      if (tables.First().Type == null)
      {
        Console.WriteLine("Table '{0}' has no type definition", tableName);
        return;
      }

      var columns = from column in tables.First().Type.Columns select column;
      if (columns.Count() == 0)
      {
        Console.WriteLine("Table '{0}' has no columns defined", tableName);
        return;
      }

      var primaryKey = from key in columns where key.IsPrimaryKey select key;
      if (primaryKey.Count() == 0)
      {
        Console.WriteLine("Table '{0}' has no primary key", tableName);
        return;
      }

      if (primaryKey.Count() > 1)
      {
        Console.WriteLine("Table '{0}' has multiple primary keys defined", tableName);
        return;
      }

      Console.WriteLine("Table {0}'s primary key is {1}", tables.First().Type.Name, primaryKey.First().Name);
      Console.WriteLine();

      Console.WriteLine("Demo of using generated enumeration classes ...");
      Console.WriteLine("-----------------------------------------------");
      Console.WriteLine("ColumnType.Int.GetFullSqlDataType()        = {0}", ColumnType.Find("Int").GetFullSqlDataType());
      Console.WriteLine("ColumnType.NVarChar.GetFullSqlDataType(20) = {0}", ColumnType.Find("NVarChar").GetFullSqlDataType(20));
    }
    #endregion
  }
}
